<template>
  <el-card>
    <el-form label-width="120px" class="exchange-form">
      <el-form-item label="当前实时汇率">
        <el-input v-model="rate" readonly style="width: 200px;" />
        <el-button @click="fetchRate" :loading="loading" style="margin-left: 8px;">刷新汇率</el-button>
      </el-form-item>
      <el-form-item label="汇率差">
        <el-input-number v-model="rateDiff" :step="0.00001" :precision="5" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="实际汇率">
        <el-input :value="actualRate" readonly style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveRate">保存</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import exchangeRateService from '@/services/exchangeRateService'

const rate = ref('')
const rateDiff = ref(0)
const loading = ref(false)

const actualRate = computed(() => {
  const r = parseFloat(rate.value)
  if (isNaN(r)) return ''
  // 向上取整到小数点后4位
  const result = r + rateDiff.value
  const roundedResult = Math.ceil(result * 10000) / 10000
  return roundedResult.toFixed(4)
})

async function fetchRate() {
  loading.value = true
  try {
    // 使用 exchangerate-api.com 获取 USD 汇率，再计算 JPY→CNY
    // https://api.exchangerate-api.com/v4/latest/USD
    const res = await fetch('https://api.exchangerate-api.com/v4/latest/USD')
    const data = await res.json()
    if (data && data.rates && data.rates.CNY && data.rates.JPY) {
      // 1 JPY = (CNY/USD) / (JPY/USD) = CNY/JPY
      const cnyPerUsd = data.rates.CNY
      const jpyPerUsd = data.rates.JPY
      const jpyToCny = cnyPerUsd / jpyPerUsd
      rate.value = jpyToCny.toFixed(5)
      ElMessage.success('汇率已更新')
    } else {
      ElMessage.error('获取汇率失败')
    }
  } catch (e) {
    ElMessage.error('获取汇率失败')
  } finally {
    loading.value = false
  }
}

function saveRate() {
  // 调用汇率服务更新汇率，实现联动
  try {
    const newRate = actualRate.value
    console.log('保存实际汇率:', newRate)
    console.log('当前实时汇率:', rate.value)
    console.log('汇率差:', rateDiff.value)
    
    exchangeRateService.setRate(newRate, '管理员')
    
    // 同时保存到本地存储作为备份
    localStorage.setItem('exchangeRate', newRate)
    localStorage.setItem('exchangeRateDiff', rateDiff.value.toString())
    
    console.log('localStorage中保存的汇率:', localStorage.getItem('exchangeRate'))
    
    ElMessage.success('汇率设置已保存并同步到所有相关页面')
  } catch (error: any) {
    ElMessage.error('保存汇率失败：' + (error.message || '未知错误'))
  }
}

onMounted(() => {
  // 初始化时拉取汇率和本地差值
  fetchRate()
  const diff = localStorage.getItem('exchangeRateDiff')
  if (diff) rateDiff.value = parseFloat(diff)
  
  // 从汇率服务获取当前汇率作为初始值
  const currentRate = exchangeRateService.getCurrentRate()
  if (currentRate && currentRate !== '0.052') {
    // 如果汇率服务中有非默认汇率，使用它
    const rateNum = parseFloat(currentRate)
    if (!isNaN(rateNum)) {
      // 计算实时汇率，使得实际汇率等于保存的汇率
      const actualRateNum = rateNum
      const realTimeRate = actualRateNum - rateDiff.value
      rate.value = realTimeRate.toFixed(6)
    }
  }
})
</script>

<style scoped>
.exchange-form {
  max-width: 480px;
  margin: 40px auto;
}
</style> 